using System.ComponentModel.DataAnnotations;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Nodes;
using iOSForLife.Data;
using iOSForLife.Data.Models;
using iOSForLife.WebAPI.IdentityModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace iOSForLife.WebAPI.Controllers;

[ApiController]
[Route("[controller]")]
public class UserController(
    IDbContextFactory<LifeContext> dbContextFactory,
    JwtHelper jwtHelper,
    IHttpClientFactory httpClientFactory,
    IHttpContextAccessor httpContextAccessor) : ControllerBase
{
    [TokenActionFilter]
    [Authorize]
    [HttpGet]
    public async Task<ActionResult<string>> GetData()
    {
        var member = httpContextAccessor.HttpContext?.User.GetUser();
        if (member == null) return NotFound("用户未登录或验证已超时");

        await using var context = await dbContextFactory.CreateDbContextAsync();
        member = await context.Users
            .Include(x => x.Todos)
            .Include(x => x.Clipboard)
            .Include(x => x.UserData)
            .FirstOrDefaultAsync(x => x.UserId == member.UserId && x.UserName == member.UserName);
        if (member == null) return NotFound("找不到用户");

        var compressAfterByte = GZipServer.Compress(JsonSerializer.SerializeToUtf8Bytes(member));
        return Convert.ToBase64String(compressAfterByte);
    }


    [HttpPost]
    public async Task<ActionResult<string>> Login(LoginModel login)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();
        var user = await context.Users.FirstOrDefaultAsync(x => x.UserId == login.Id && x.UserName == login.Name);
        if (user != null) return jwtHelper.GetMemberToken(user);

        var client = httpClientFactory.CreateClient();
        var response = await client.PostAsJsonAsync("https://www.xauat.site/api/Member/Login", login);
        if (!response.IsSuccessStatusCode) return NotFound("未找到iMember身份信息");

        var Jwt = await response.Content.ReadAsStringAsync();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        response = await client.GetAsync("https://www.xauat.site/api/Member/GetData");

        if (!response.IsSuccessStatusCode) return NotFound("iMember异常");

        var json = await response.Content.ReadAsStringAsync();
        var jsonDoc = JsonNode.Parse(json);
        if (jsonDoc == null) return NotFound("iMember异常");
        var userData = new UserModel()
        {
            UserName = jsonDoc["userName"]?.GetValue<string>() ?? "",
            UserId = jsonDoc["userId"]?.GetValue<string>() ?? "",
            Identity = jsonDoc["identity"]?.GetValue<string>() ?? "",
            Gender = jsonDoc["gender"]?.GetValue<string>() ?? "",
            PhoneNum = jsonDoc["phoneNum"]?.GetValue<string>() ?? "",
            ClassName = jsonDoc["className"]?.GetValue<string>() ?? ""
        };

        if (userData.Identity != "Member") userData.Identity = "Admin";
        context.Users.Add(userData);

        await context.SaveChangesAsync();
        return jwtHelper.GetMemberToken(userData);
    }
}

public class LoginModel
{
    [Required]
    [StringLength(15, ErrorMessage = "请正确输入姓名")]
    public string Name { get; set; } = "";

    [Required]
    [StringLength(10, ErrorMessage = "请正确输入学号")]
    public string Id { get; set; } = "";
}